/*  
 * cafe-gistools.js
 * @Author :      GUORUI
 * @CreateDate :  2017年6月23日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	
	/**
	 * 获取地图区域上下级关系 （）
	 */
	function getMapInfo(mapId){
		var returnObj = {};
		//获取地图信息
		var GLMap=mapObj[mapId];
		var GIS = GLMap.geometryData.areaconfig;
		for(var code in GIS){
			if(code.length>=6 && code.startsWith("35")){
				if(code.length==6){
					var superior = code.substring(0,4);		//上级
					if(returnObj[superior] && $.isArray(returnObj[superior])){
						var array = returnObj[superior];
							array.push(GIS[code]);
						returnObj[superior] = array;
					}else{
						returnObj[superior] = [GIS[code]];
					}
				}else if(code.length==9){
					var superior = code.substring(0,6);		//上级
					if(returnObj[superior] && $.isArray(returnObj[superior])){
						var array = returnObj[superior];
							array.push(GIS[code]);
						returnObj[superior] = array;
					}else{
						returnObj[superior] = [GIS[code]];
					}
				}
			}
		}
		return returnObj;
	}
	
	/**
	 * 创建控件界面
	 */
	function getNodeHtml(cfg){
		var icons = "";
		for(var key in cfg){
			var each = "<div item='"+key+"' class='eachGroup'>";
			var iconArray = cfg[key];
			var i=0;
			do{
				var eachIconInfo = iconArray[i];
				each += "<div class='iconCommon "+eachIconInfo.icon+"' operator='"+eachIconInfo.id+"' title='"+eachIconInfo.name+"'></div>";
				i++;
			}while(i<iconArray.length);
			each+="</div>";
			icons = icons + each;
		}
		
		var html = "<div class='drawToolPart'>"
				+ 		"<div class='drawShowOrHide'>绘制</div>"
				+ 		"<div class='drawIcon'>" 
				+			"<div class='changeIcon' title='切换'></div>"
				+			icons	
				+ 		"</div>"
				+  "</div>";
		return $(html);
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,params){
		//绘制按钮
		$drop.find(".drawShowOrHide").off("click").on("click",function(){
			if($(this).hasClass("active")){
				$(this).removeClass("active");
				$(this).siblings(".drawIcon").hide();
			}else{
				$(this).addClass("active");
				$(this).siblings(".drawIcon").show();
			}
		})
		//切换按钮
		$drop.find(".changeIcon").off("click").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var item = $(this).attr("item");
				if(item=="0"){				//行政区
					$(this).attr("item","1");
					$(this).siblings(".eachGroup[item='0']").hide();
					$(this).siblings(".eachGroup[item='1']").show();
				}else if(item=="1"){		//落区
					$(this).attr("item","0");
					$(this).siblings(".eachGroup[item='1']").hide();
					$(this).siblings(".eachGroup[item='0']").show();
				}
				//去除之前选中的操作
				var olds = $(".eachGroup[item='"+item+"']").find(".iconCommon.active").removeClass("active");
				clearState(item,olds,params);
			}
		})
		//操作按钮
		$drop.find(".iconCommon").off("click").on("click",function(){
			var type = $(this).parents().attr("item");
			var operator = $(this).attr("operator");
			//非置灰状态下
			if(!$(this).hasClass("disabled")){
				var old_operator = $(this).closest(".eachGroup").find(".active");
				clearState(type,old_operator,params);			//清除之前的操作
				if(type=="1"){							//落区
					if($(this).hasClass("active")){
						$(this).removeClass("active");
					}else{
						$(this).addClass("active");
						$(this).siblings().removeClass("active");
						callGisFun(type,operator,params);
					}
				}else if(type=="0"){					//行政区
					if($(this).hasClass("active")){
						if(operator=="xzq"){    //全选被选中不能再次点击
							
						}else{
							$(this).removeClass("active");
						}		
					}else{
						$(this).addClass("active");
						if(operator=="clear"){    
							$(this).siblings().not(".iconCommon[operator='xzq']").removeClass("active");
						}else if(operator=="signal"){
							$(this).siblings().not(".iconCommon[operator='xzq']").removeClass("active");
						}else if(operator=="xzq"){
							$(this).siblings().removeClass("active");
						}
						callGisFun(type,operator,params);
					}
				}
			}
		})
	}
	
	
	/**
	 * 初始化工具条展示
	 * item - 0/1
	 */
	function initShow(item){
		$(".drawToolPart .drawIcon .changeIcon").attr("item",item);
		$(".drawToolPart .drawIcon .eachGroup").hide();
		$(".drawToolPart .drawIcon .eachGroup[item='"+item+"']").show();
		
		$(".drawToolPart .drawIcon .eachGroup .iconCommon").addClass("disabled");
		$(".drawToolPart .drawIcon .eachGroup .iconCommon").removeClass("active");
		for(var i=0;i<showInit.length;i++){
			$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+showInit[i]+"']").removeClass("disabled");
		}
	}
	
	/**
	 * 清除状态
	 */
	function clearState(type,olds,params){
		$.each(olds,function(){
			var old_operator = $(this).attr("operator");
			if(type=="1"){			//落区
				if("lq" == old_operator){
					GIS.Draw.endDraw(params.gisId,params.layerId);
				}else if("edit" == old_operator){
					GIS.Edit.endEdit(params.gisId,[params.layerId]);
				}else if("clear" == old_operator){
					GIS.Edit.setState(params.gisId,params.layerId,"deleting",false);
				}
			}else if(type=="0"){	//行政区
				//结束点选 操作
				if('signal'==old_operator){
					GIS.Draw.endDraw(params.gisId,"gt-draw-temp");
				}else if("clear" == old_operator){
					GIS.Edit.setState(params.gisId,params.layerId,"multideleting",false);
				}else if('xzq'==old_operator){
					
				}
			}
		})
	}
	
	/**
	 * 调用GIS方法
	 */
	function callGisFun(type,operator,params){
		if(type=="1"){			/**落区**/
			if(operator=="lq"){					//绘制
				GIS.Draw.selectRegions(params.gisId,[params.layerId],params.baseDataUrl,
						{
							supernames : params.supernames,
							bShowRegion : false,
							polygonStyle : params.getStyle(),
							makeType : params.getMakeType(),
							call:function(result,layerId,reGra){
								if(result){
									//切换按钮置灰
									$(".drawToolPart .drawIcon .changeIcon").addClass("disabled");
									//移除选中并 放开 编辑、删除按钮
									$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+operator+"']").removeClass("active");
									$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+operator+"']").siblings().removeClass("disabled");
									//结束绘制、设置高亮
									GIS.Draw.endDraw(params.gisId,layerId);
									GIS.Graphic.highlight(params.gisId,layerId,{"strokeStyle" : "rgb(0, 0, 0)", "lineWidth" : 2},true);
									//回调
									if($.isFunction(params.call)){
										params.call({
											isAreaDraw:type,
											type:"lq",
											data:result,
											layerId:layerId,
											reGra:reGra
										});
									}
								}
								
							}
						}
					);
			}else if(operator=="edit"){			//编辑
				GIS.Edit.startEdit(params.gisId,[params.layerId],
						{
							call:function(graphic,reGra){
								var result = GIS.Select.polygons(params.gisId,GLMap.geometryData.areaconfig,graphic,{supernames : params.supernames});
								var newResult = [];
								for(var i=0;i<result.length;i++){
									var eachInfo = {
										"SuperName" : result[i].SuperName,
										"areacode" : result[i].areacode,
										"name" : result[i].name,
									}
									newResult.push(eachInfo);
								}
								if($.isFunction(params.call)){
									params.call({
										isAreaDraw:type,
										type:"lq-edit",
										data:newResult,
										layerId:params.layerId,
										reGra:reGra
									});
								}
							},
							editNum:1
						}
					);
			}else if(operator=="clear"){		//删除
				GIS.Edit.setState(params.gisId,params.layerId,"deleting",true,function(reGra,delNum){
					if(0 == delNum){
						GIS.Edit.setState(params.gisId,params.layerId,"deleting",false);
						initShow(type);
					}
					if($.isFunction(params.call)){
						params.call({
							isAreaDraw:type,
							type:"lq-clear",
							reGra:reGra
						});
					}
				});
			}
		}else if(type=="0"){	/**行政区**/
			if(operator=="xzq"){			//全选
				var style = params.getStyle();
					style.bUnion = true;		//图标合并
				var options = {
					style : style, 
					showAllByArea : true,  
					supername : params.supernames,
					groupId : params.getGroupId()
				}
				var returnInfo = GIS.Graphic.showWarnArea(params.gisId,params.layerId,null,options);  
				//设置高亮
				GIS.Graphic.highlight(params.gisId,params.layerId,{"strokeStyle" : "rgb(0, 0, 0)", "lineWidth" : 2},true);
				//控制按钮
				$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+operator+"']").siblings().removeClass("disabled");
				//切换按钮置灰
				$(".drawToolPart .drawIcon .changeIcon").addClass("disabled");
				
				if($.isFunction(params.call)){
					params.call({
						isAreaDraw:type,
						type:"xzq",
						data:returnInfo.data,
						reGra:returnInfo.group,
						layerId:returnInfo.layerId
					});
				}
			}else if(operator=="signal"){   	//点选	
				var style = params.getStyle();
					style.bUnion = true;		//图标合并	
					console.log(style.picUrl);
				var makeType =  params.getMakeType();
				var count = 0;
				if(user.codeId == "35" && makeType=="1"){		//市台预警信号   330205-江北
					count = params.areaInfo["330205"].length;		
				}else{
					count = params.areaInfo[user.codeId].length;
				}	
				GIS.Draw.selectRegions(params.gisId,["gt-draw-temp",params.layerId],params.baseDataUrl,
					{
						supernames : params.supernames,
						bPick : true,
						regionStyle : style,
						makeType : makeType,
						groupId : params.getGroupId(),
						call:function(result,layerId,reGra){
							//设置高亮
							GIS.Graphic.highlight(params.gisId,layerId,{"strokeStyle" : "rgb(0, 0, 0)", "lineWidth" : 2},true);
							//控制按钮
							$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+operator+"']").siblings().removeClass("disabled");
							//切换按钮置灰
							$(".drawToolPart .drawIcon .changeIcon").addClass("disabled");
							//全选按钮
							if(result.length == count){
								$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='xzq']").addClass("active");
							}
							params.call({
								isAreaDraw:type,
								type:"xzq-edit",
								layerId:layerId,
								data:result,
								reGra:reGra
							});
						},
						removeCall : function(result,layerId,reGra){
							//全选按钮
							$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='xzq']").removeClass("active");
							if(result.length==0){
								//删除按钮
								$(".drawToolPart .drawIcon .eachGroup .iconCommon[operator='"+operator+"']").siblings(".iconCommon[operator='clear']").addClass("disabled");
							}
							params.call({
								isAreaDraw:type,
								type:"xzq-edit",
								layerId:layerId,
								data:result,
								reGra:reGra
							});
						}
					}
				)
			}else if(operator=="clear"){	//删除
				GIS.Edit.setState(params.gisId,params.layerId,"multideleting",true,function(result,layerId,reGra,gNum){
					if(0 == gNum){
						initShow(type);
					}
					if($.isFunction(params.call)){
						params.call({
							isAreaDraw:type,
							type:"xzq-clear",
							reGra:reGra,
							layerId:layerId
						});
					}
				});
			}
		}
	}
	
	/**
	 * 绘制工具条按钮
	 * 0-行政区   1-落区
	 */
	var gisTools = {
		 "0" : [
		     {id:"xzq",name : "全选",icon : "gistools-jyxzq-icon"},
		     {id:"signal",name : "点选",icon : "gistools-bjxzq-icon"},
		     {id:"clear",name : "删除",icon : "gistools-sc-icon"}
		 ],
		 "1" : [
	        {id:"lq",name : "绘制落区",icon : "gistools-zx-icon"},   
	        {id:"edit",name : "编辑",icon : "gistools-bj-icon"},
	        {id:"clear",name : "删除",icon : "gistools-sc-icon"}
         ]
	};
	
	/**
	 * 初始化显示的图标 id
	 */
	var showInit = ["xzq","signal","lq"];
	
	/**
	 * 控件构造函数
	 */
	var CFGistools = function(settings){
		var options = {
			baseDataUrl : '' ,	//Gis文件路径
			appendTo: null,		//控件所在容器
			gisId : null,		//GIS地图的id
			supernames : ["宁波市"],
			layerId : "draw-gis-map",//图层Id
			call : null,			 //GIS操作完成后的回调函数
			getStyle : function(){   //获取样式
				return {fillStyle:"rgb(0,0,255)",strokeStyle:"rgb(0,0,255)"}
			},
			getMakeType : null,	//获取制作类型（全市预警、预警信号）
			getGroupId : null,	//获取当前选择编辑的行政区分组id 
			initShow : "1"		//默认展示
		};

		this.config = $.extend(options,settings);
		this.config.areaInfo = getMapInfo(this.config.gisId);		//地图区域信息
		
		var $html = getNodeHtml(gisTools);
		if(this.config.appendTo){
			this.config.appendTo.empty().append($html);
			initShow(this.config.initShow);
			_eves($html,this.config);
		}
		this.$drop = $html;
	}
	/**
	 * 控件对外提供的方法
	 */
	CFGistools.prototype = {
		//更改config
		upConfig : function(config){
			this.config = $.extend(this.config,config);
		},
		//展开工具条、并根据制作类型、区域绘制类型、区域显示行政区还是落区操作按钮
		initDrawTool : function(type){		//0行政区   //1落区
			//展开
			if(this.$drop.find(".drawShowOrHide").hasClass("active")){
				
			}else{
				this.$drop.find(".drawShowOrHide").trigger("click");
			}
			
			if(type=="0"||type=="1"){
				//切换按钮
				this.$drop.find(".changeIcon").addClass("disabled");
			}else{
				//切换按钮
				this.$drop.find(".changeIcon").removeClass("disabled");
			}
			
			if(!(type=="0"||type=="1")){
				//显示按钮
				var codeId = user.codeId;
				var type;
				var makeType = this.config.getMakeType();
				//市区
				if(codeId=="35"){		//makeType- 0(全市预警) 1(预警信号)
					if("1" == makeType){
						type = "0";
					}else{
						type = "1";
					}
				}else{
					type = "0";
				}
			}
			initShow(type);
		},	
		//自定义显示按钮 -- 修改的时候用     
		defineTool : function(gisData){
			//展开
			if(this.$drop.find(".drawShowOrHide").hasClass("active")){
				
			}else{
				this.$drop.find(".drawShowOrHide").trigger("click");
			}
			//置灰切换图标
			this.$drop.find(".changeIcon").addClass("disabled");
			//全部置灰
			this.disabled();
			//控制显示
			var showIcon = [];
			var isAreaDraw = gisData.isAreaDraw;
			if(isAreaDraw=="0"){			//行政区
				showIcon = ["xzq","signal","clear"];
				//全选	
				var data = gisData.data;
				var subCode = []; 	//存放上级的code
				var total = 0;		//下级总数
				for(var k=0;k<data.length;k++){
					var eachCode = data[k].areacode;
					if(eachCode.length==6){
						var sub = eachCode.substring(0,4);
					}else if(eachCode.length==9){
						var sub = eachCode.substring(0,6);
					}
					if(typeof sub != "undefined" && typeof sub == "string" && ($.inArray(sub,subCode)==-1)){
						subCode.push(sub);
						total = total + this.config.areaInfo[sub].length;
					}
				}
				if(total>0&&total==data.length){
					this.$drop.find(".eachGroup[item="+isAreaDraw+"]").find(".iconCommon[operator='xzq']").addClass("active");
				}
			}else if(isAreaDraw="1"){
				showIcon = ["lq","edit","clear"];
			}
		
			this.$drop.find(".eachGroup").hide();
			this.$drop.find(".eachGroup[item="+isAreaDraw+"]").show();
			for(var i=0;i<showIcon.length;i++){
				var operator = showIcon[i];
				this.$drop.find(".eachGroup[item="+isAreaDraw+"]").find(".iconCommon[operator="+operator+"]").removeClass("disabled");
			}
			//更改配置
			this.config["layerId"] = gisData.layerId;
		},
		//全部置灰 - 并结束工具按钮操作
		disabled : function(){
			var nowActive = this.$drop.find(".iconCommon.active");	//当前选中
			if(nowActive.length>0){
				var type = nowActive.closest(".eachGroup").attr("item");
				var params = this.config;
				clearState(type,nowActive,params);
			}
			this.$drop.find(".iconCommon").addClass("disabled");
			//切换按钮
			this.$drop.find(".changeIcon").addClass("disabled");
		},
		//重新调用gis方法
		setDrawState : function(){
			var type = this.$drop.find(".changeIcon").attr("item");
			if(type=="1") { 		 //落区
				var $operator = this.$drop.find(".eachGroup[item='"+type+"']").find(".active");
				var operator = $operator.attr("operator");
				clearState(type,$operator,this.config);				//清除之前的操作
				if(operator){
					callGisFun(type,operator,this.config);			//再次调用操作
				}
			}else if(type=='0'){    //行政区
				var config = this.config;
				var $operator = this.$drop.find(".eachGroup[item='"+type+"']").find(".active");
					clearState(type,$operator,config);			//清除之前的操作
				$.each($operator,function(){
					var operator = $(this).attr("operator");
					if("signal"==operator){
						callGisFun(type,operator,config);		//再次调用操作
					}
				})
			}
		}
	};
	
	CafeJS.DrawWarn = function(settings){
		var drop = new CFGistools(settings);
		return drop;
	}
});